package org.example.school.service.impl;



import lombok.extern.slf4j.Slf4j;
import org.example.school.service.CommonService;
import org.example.school.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Service
@Slf4j
public class CommonServiceImpl implements CommonService {
    @Autowired
    AliOssUtil aliOssUtil;

    @Override
    public String upload(MultipartFile file) {
        String filePath = null;
        try {
            // 原始文件名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || originalFilename.isEmpty()) {
                throw new IllegalArgumentException("文件名不能为空");
            }
            // 截取后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 构造新的文件名
            String objectName = UUID.randomUUID() + extension; // 随机文件名
            filePath = aliOssUtil.upload(file.getBytes(), objectName);
            log.info("文件上传成功，路径: {}", filePath); // 添加日志记录
        } catch (IOException e) {
            log.error("文件上传失败:{}", e.getMessage(), e);
            throw new RuntimeException("文件上传失败，请稍后重试");
        }
        return filePath;
    }
}
